package org.laobai.permission.service.impl;

import org.laobai.permission.entity.Area;
import org.laobai.permission.mapper.AreaMapper;
import org.laobai.permission.service.AreaService;
import org.laobai.permission.struct.PageResult;
import org.laobai.permission.vo.SearchVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiusan
 * @since 2021-11-17
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Override
    public PageResult<Area> page(Integer currPage, Integer pageSize, SearchVO vo) {
        // 分页
        Page<Area> areaPage = new Page<>(currPage, pageSize);

        // 条件查询
        QueryWrapper<Area> wrapper = new QueryWrapper<>();

        if (Objects.nonNull(vo)) {
            String keyWord = vo.getKeyWord();
            if (!StringUtils.isEmpty(keyWord)) {
                wrapper.like("name", keyWord);
            }
        }
        areaPage = page(areaPage, wrapper);
        return PageResult.of(areaPage.getRecords(), areaPage.getTotal());
    }

    @Override
    public boolean saveArea(Area area) {
        return save(area);
    }

    @Override
    public boolean updateArea(Area area) {
        return updateById(area);
    }

    @Override
    public boolean delById(Long id) {
        return removeById(id);
    }

    @Override
    public boolean delByIds(List<Long> ids) {
        return removeByIds(ids);
    }

    @Override
    // @Cacheable("tree")
    public List<Area> getTree() {
        List<Area> list = list();

        return getTree(list, 1);
    }

    private List<Area> getTree(List<Area> list, Integer pid) {
        List<Area> areas = new ArrayList<>();
        list.forEach(item -> {
            if (item.getPid().equals(pid)) {
                areas.add(item);
                // 获取子节点
                List<Area> children = getTree(list, item.getId());

                if (!children.isEmpty()) {
                    item.setChildren(children);
                }
            }
        });


        return areas;
    }
}
